# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

import pymongo
import redis
import csv

class RedisPipeline:
    def open_spider(self, spider):
        if spider.name == "producter":
            self.client = redis.Redis()
            self.client.delete("tasks")

    def process_item(self, item, spider):
        if spider.name == "producter":
            self.client.lpush("tasks", json.dumps({
                    "url": "https://httpbin.org/post",
                    "meta": {
                    },
                    "data":item,
                    "method":"POST",
                }, ensure_ascii=False))
            return item

    def close_spider(self, spider):
        if spider.name == "producter":
            self.client.close()


# class CSVPipeline:
#     def open_spider(self, spider):
#         self.file = open('quotes.csv', 'w')
#         self.writer = csv.writer(self.file)
#         self.writer.writerow(['id', 'content', 'author', 'tags'])
#
#
#     def process_item(self, item, spider):
#         pass
#
#     def close_spider(self, spider):
#         pass
#
#
# class MongoDBPipeline:
#     def open_spider(self, spider):
#         self.client = pymongo.MongoClient('localhost', 27017)
#         self.db = self.client.get_database("toscrape")
#         self.collections = self.db.get_collection("items")
#         self.items = []
#
#     def process_item(self, item, spider):
#
#         item = dict(item)
#         self.items.append(item)
#         if len(self.items) == 10:
#             self.collections.insert_many(self.items)
#             self.items.clear()
#         return item
#
#     def close_spider(self, spider):
#         if len(self.items) > 0:
#             self.collections.insert_many(self.items)
#             self.items.clear()
#         self.client.close()